<?php
namespace app\data\service;
use think\admin\Library;
use app\data\model\DataMember;
use app\data\service\JwtTokenService;
class MemberService
{
    //用户登录
    function login($data,$code){
        if($code!=cache('sms_code'.$data['mobile'])){
            return ['code'=>0,'data'=>'','message'=>'验证码错误'];
        }
        $map = ['mobile'=>$data['mobile']];
        $memberInfo  = DataMember::mk()->where($map)->find();
        if($memberInfo['status'] == 0){
            return  ['code'=>0,'data'=>'','message'=>'用户被禁用'];
        }
        DataMember::mk()->startTrans();
        try {
            if(empty($memberInfo)){
                $data=[
                    'mobile'=>$data['mobile'],
                ];
                $id = DataMember::mk()->insertGetId($data);
                $memberInfo  = DataMember::mk()->find($id);
            }
            DataMember::mk()->commit();
        }catch (Exception $e) {
            return json_encode(['code'=>0,'data'=>'','message'=> $e->getMessage()]);
            $query->rollback();
        }
        $jwt = new JwtToken();
        $token = $jwt->sign_token($memberInfo);
        $data=[
            'token'=>$token,
            'user'=>[
                'id'=>$memberInfo['id'],
                'nickname'=>$memberInfo['nickname'],
                'mobile'=>$memberInfo['mobile'],
                'avatar'=>$memberInfo['avatar'],
            ],
        ];
        return json(['code'=>1,'data'=>$data,'message'=>'']);
    }
}
